﻿

namespace Forest.Lion.Data.SqlServer.Repositories {
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using Forest.Lion.Model;

    public class LovRepository : BaseRepository, ILovRepository {
        public LovRepository(IUnitOfWork unitOfWork)
            : base(unitOfWork) {
        }
        public void Create(Lov lov) {
            this.GetDbSet<Lov>().Add(lov);
            this.UnitOfWork.SaveChanges();
        }

        public Lov GetLov(Guid lovId) {
            return this.GetDbSet<Lov>()
                .Where(c => c.Id == lovId)
                .Single();
        }

        public void Update(Lov updatedLov) {
            this.GetDbSet<Lov>().Attach(updatedLov);
            this.SetEntityState(updatedLov, updatedLov.Id == Guid.Empty
                ? EntityState.Added
                : EntityState.Modified);
            this.UnitOfWork.SaveChanges();
        }

        public void Delete(Guid lovId) {
            Lov lovToDelete = this.GetLov(lovId);
            this.GetDbSet<Lov>().Remove(lovToDelete);
            this.UnitOfWork.SaveChanges();
        }

        public IEnumerable<Lov> Find() {
            return this.GetDbSet<Lov>().ToList();
        }

        public IEnumerable<Lov> GetAll() {
            return this.GetDbSet<Lov>().ToList();
        }

        public IEnumerable<Lov> GetListByParentId(Guid parentId) {
            return this.GetDbSet<Lov>().Where(l => l.ParentId == parentId)
                .OrderBy(l => l.SortOrder);
        }

        public IEnumerable<Lov> GetSubListByParentId(Guid parentId)
        {
            var resultList = from subItem in this.GetDbSet<Lov>()
                             join item in GetListByParentId(parentId)
                             on subItem.ParentId equals item.Id
                             select subItem;
            return resultList;
        }
    }

}
